#include "wrap.h"
#include "tcp.h"
void *do_work(void *arg)
{
    char buf[1024];
    int len, i;
    int cfd = (int)arg;
    //int pthread_detach(pthread_t phread)
    pthread_detach(pthread_self());//线程结束自动退出,pthread_self();获取自己的pid
    while (1) {
        len = Read(cfd, buf, sizeof(buf));
        if (len <= 0)
            break;
        // Write(STDOUT_FILENO, buf, len);//printf("%s\r\n", buf);
        printf(" %d :%s\r\n", cfd,buf);
        for (i = 0; i < len; ++i)
            buf[i] = toupper(buf[i]);//把小写字母转换为大写字母。
        Write(cfd, buf, len);
    }
    Close(cfd);
    return 0;//只能调return 0 不能调exit 0 不然就是终止进程了
}

int main(int argc, char *argv[])
{
    int ser_socket, cfd;//
    int serv_port = SERV_PORT;
    char client_ip[128];
    struct sockaddr_in serv_addr, client_addr;
    socklen_t client_len;
    pthread_t tid;

    if (argc == 2) 
        serv_port = atoi(argv[1]);

    ser_socket = Socket(AF_INET, SOCK_STREAM, 0);//创建套接字

    bzero(&serv_addr, sizeof(serv_addr));//清零结构体
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons((short)serv_port);
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    Bind(ser_socket, (struct sockaddr *)&serv_addr, sizeof(serv_addr));//绑定,套接字ip绑定

    Listen(ser_socket, 128);//监听,套接字与最大连接个数
    printf("wait for connect...\n");

    while (1) {
        client_len = sizeof(client_addr);
        cfd = Accept(ser_socket, (struct sockaddr *)&client_addr, &client_len);//accept返回时传出客户端的地址和端口号
        printf("client:%s\t%d\n",
                inet_ntop(AF_INET, &client_addr.sin_addr.s_addr, client_ip, sizeof(client_ip)),
                ntohs(client_addr.sin_port));//inet_ntop将网络传输的二进制数值转化为成点分十进制的ip地址,ntohs将一个16位数由网络字节顺序转换为主机字节顺序。
        /*
         int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);
        参数一：线程id，传入传出参数
        参数二：线程初始化参数列表 NULL表示默认
        参数三：线程任务函数
        参数四：参数三的传入传出参数，需要强转(void*)
        */
        pthread_create(&tid, NULL, do_work, (void *)cfd);
    }

    return 0;
}